<template>
  <div class="flex justify-between items-center mb-3">
    <!-- 左侧 -->
    <div class="flex items-center">
      <EditButton
        v-for="(btn, index) in leftBtnList"
        :key="btn.id"
        :btn="btn"
        @update="Object.assign(btn, $event)"
        @remove="onRemoveLeft(index)"
        @edit-modal="$emit('open', btn)"
        @edit-dropdown="btn.dropdownVisible = true"
      />
      <div>
        <a-dropdown :trigger="['click']">
          <a-button type="dashed" block>
            <PlusOutlined />
          </a-button>
          <template #overlay>
            <a-menu @click="addLeftItem">
              <span class="text-gray-300 cursor-default text-center inline-block w-full dark:text-gray-600"
                >预设</span
              >
              <a-divider class="my-0.5"></a-divider>
              <template v-if="noAddedPresets.length">
                <a-menu-item v-for="item in noAddedPresets" :key="item.key">{{ item.label }}</a-menu-item>
              </template>
              <span v-else class="text-sm text-gray-300 dark:text-gray-600 cursor-default"
                >已设置全部预设</span
              >

              <a-divider class="my-0.5"></a-divider>
              <a-menu-item key="diy" class="text-gray-300 cursor-default text-center inline-block w-full"
                >自定义</a-menu-item
              >
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>

    <!-- 右侧 -->
    <div>
      <a-button type="dashed" shape="circle" :icon="h(RedoOutlined)" />
    </div>
  </div>
</template>

<script setup lang="ts" name="operation-row">
import { RedoOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import type { MenuClickEventHandler } from 'ant-design-vue/es/menu/src/interface'
import { AnyButton } from '@/form'
import { keyModal } from '../key'

import { createBtnUtils } from '@/utils/create'
import { capitalize } from '@/utils/tool'

const { id, formItems } = inject(keyModal)!
watch(
  formItems,
  (items) => {
    const target = leftBtnList.find((btn) => btn.id === id.value)!
    target.modal!.modalInfo = [...items]
  },
  { deep: true }
)

defineEmits<{
  (event: 'open', value: AnyButton): void
}>()

const presetTypes = reactive([
  { key: 'add', label: '新增' },
  { key: 'delete', label: '删除' },
  { key: 'export', label: '导出' },
  { key: 'import', label: '批导' }
])

const leftBtnList: AnyButton[] = reactive([createBtnUtils.createAdd(), createBtnUtils.createDelete()])
const noAddedPresets = computed(() =>
  presetTypes.filter((type) => !leftBtnList.map((item) => item.label).includes(type.label))
)

const addLeftItem: MenuClickEventHandler = ({ key }) => {
  leftBtnList.push(createBtnUtils[`create${capitalize(key as string)}`]())
}

const onRemoveLeft = (index: number) => {
  leftBtnList.splice(index, 1)
}
</script>

<style scoped></style>
